package com.yyfax.ph.common.location;

import android.content.Context;

import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;

public class LocationPresenter extends Presenter<Model, LocationPresenter.View> {
	private View mView;
	private LocationManager mLocationManager;

	public interface View extends IView {
		void onGetCitySuccess(String city, boolean isManual);

		void onGetCityFailure(boolean isManual);
	}

	public static class Generator implements PresenterFactory<LocationPresenter> {
		@Override
		public LocationPresenter create() {
			return new LocationPresenter();
		}
	}

	@Override
	public void attach(View view) {
		mView = view;
	}

	@Override
	public void detach() {
		if (mLocationManager != null) {
			mLocationManager.setLocationListener(null);
			mLocationManager.stopLocation();
//		mLocationManager.releaseLocation();
			mLocationManager = null;//解决内存泄漏， mLocationManager持有ctx引用
		}
		mView = null;
	}

	public void createModel(Context ctx) {
		mLocationManager = LocationManager.getInstance(ctx);
	}

	public void getLocation(Context ctx, final boolean isManual) {
		if (mLocationManager == null){
			createModel(ctx);
		}
		mLocationManager.startLocation(new LocationManager.LocationListener() {
			@Override
			public void onLocationSuccess(String city) {
				if (null != mView) {
					mView.onGetCitySuccess(city, isManual);
				}
			}

			@Override
			public void onLocationFailure() {
				if (null != mView) {
					mView.onGetCityFailure(isManual);
				}
			}
		});
	}
}
